let selProvince = document.getElementById('selProvince');
let selCity = document.getElementById('selCity');
let spProvince = document.getElementById('spProvince');
let spCity = document.getElementById('spCity');

const BASE_URL = 'https://api.huhuiyu.top';
// 通过ajax获取省份信息
function queryProvince() {
  let promise = axios({
    url: BASE_URL + '/link/provinces',
    method: 'get',
    data: '',
  });

  promise
    .then((resp) => {
      console.log('服务器返回的数据:', resp.data);
      let info = resp.data;
      if (!info.success) {
        alert(info.message);
        return;
      }
      // 成功获取到信息就填写到select中
      selProvince.innerHTML = '';
      for (let i = 0; i < info.data.length; i++) {
        let pro = info.data[i];
        console.log('省份：', pro);
        //  <option value="1">湖南</option>
        // 创建option元素
        let op = document.createElement('option');
        op.append(pro.province);
        op.setAttribute('value', pro.pid);
        // 添加到省份的select中
        selProvince.append(op);
      }
      // 设置省份的默认值
      selProvince.selectedIndex = 17;
      queryCity();
    })
    .catch((err) => {
      console.error(err);
    });
}

// 联动查询城市信息
function queryCity() {
  // 显示选中的省份编号
  spProvince.innerHTML = selProvince.value;
  // 通过ajax查询省份对应的城市
  let promise = axios({
    url: `${BASE_URL}/link/cities/${selProvince.value}`,
    method: 'get',
    data: '',
  });
  promise
    .then((resp) => {
      let info = resp.data;
      if (!info.success) {
        alert(info.message);
        return;
      }
      selCity.innerHTML = '';
      for (let i = 0; i < info.data.length; i++) {
        let city = info.data[i];
        let op = document.createElement('option');
        op.append(city.city);
        op.setAttribute('value', city.cid);
        selCity.append(op);
      }
      selCity.selectedIndex = 0;
      spCity.innerHTML = selCity.value;
    })
    .catch((err) => {
      console.error(err);
    });
  
} 

selProvince.addEventListener('change', () => {
  queryCity();
});

queryProvince();

selCity.addEventListener('change', () => {
  spCity.innerHTML = selCity.value;
});

// 作业：按照上课的联动效果完成部门员工的联动查询
